<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/26
 * Time: 13:37
 */

namespace App\Model\Banners;


use App\Model\BaseModel;

class BannersModel extends BaseModel
{
    protected $table = 'siam_banners';
    protected $primaryKey = 'id';

    public function getAll(int $page = 1, string $keyword = null, int $pageSize = 10, string $field = '*'): array
    {
        if (!empty($keyword)) {
            $this->getDb()->where('title', '%' . $keyword . '%', 'like');
        }
        $list = $this->getDb()
            ->withTotalCount()
            ->orderBy($this->primaryKey, 'DESC')
            ->get($this->table, [$pageSize * ($page  - 1), $pageSize],$field);
        $total = $this->getDb()->getTotalCount();
        return ['total' => $total, 'list' => $list];
    }

    /**
     * 根据ID搜索
     * @param BannersBean $bean
     * @param string $field
     * @return BannersBean|null
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getOne(BannersBean $bean,string  $field = '*'): ?BannersBean
    {
        $info = $this->getDb()->where($this->primaryKey, $bean->getId())->getOne($this->table,$field);
        if (empty($info)) {
            return null;
        }
        return new BannersBean($info);
    }

    /**
     * 根据bean插入数据
     * @param BannersBean $bean
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function add(BannersBean $bean): bool
    {
        return $this->getDb()->insert($this->table, $bean->toArray(null, $bean::FILTER_NOT_NULL));
    }

    /**
     * 根据bean删除数据
     * @param BannersBean $bean
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function delete(BannersBean $bean): bool
    {
        return  $this->getDb()->where($this->primaryKey, $bean->getId())->delete($this->table);
    }

    /**
     * 根据bean修改数据
     * @param BannersBean $bean
     * @param array $data
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function update(BannersBean $bean, array $data): bool
    {
        if (empty($data)){
            return false;
        }
        return $this->getDb()->where($this->primaryKey, $bean->getId())->update($this->table, $data);
    }
}